from django.shortcuts import render,redirect,HttpResponse
from dbadmin import models
from saltstackadmin import settings
import subprocess
import os
import paramiko
# Create your views here.

def s_add(request):
    info = {}
    my_name = request.session.get('username')
    info["my_name"] = my_name
    if request.method == "GET":
        salt_list = models.saltconfig.objects.values()
        cmd_list = models.cmdlist.objects.values()
        info["salt_list"] = salt_list
        info["cmd_list"] = cmd_list

        return render(request,"saltconfig_add.html",info)
    else:
        s_ip = request.POST.get("s_ip")
        s_name = request.POST.get("s_name")
        login_mode = request.POST.get("login_mode")
        s_version = request.POST.get("s_version")
        s_gitlab = request.POST.get("gitlab")
        s_cmd = request.POST.getlist("s_cmd")
        file_roots = request.POST.get("file_roots")
        pillar_roots = request.POST.get("pillar_roots")


        salt_status = models.saltconfig.objects.filter(s_ip=s_ip).count()
        if salt_status == 0:
            models.saltconfig.objects.create(s_ip=s_ip,s_name=s_name,s_login=login_mode,s_version=s_version,s_gitlab=s_gitlab,s_init=0,s_file_roots=file_roots,s_pillar_roots=pillar_roots)
            id = models.saltconfig.objects.filter(s_ip=s_ip).values("id")[0]["id"]
            obj = models.saltconfig.objects.get(id=id)
            obj.s_cmd.set(s_cmd)
        else:
            pass
        return redirect("/saltconfig/add/")

def s_del(request):
    if request.method == "GET":
        id = request.GET.get("id")
        models.saltconfig.objects.filter(id=id).delete()

    else:
        pass
    return redirect("/saltconfig/add/")


def s_cmd(request):
    info = {}
    my_name = request.session.get('username')
    info["my_name"] = my_name
    if request.method == "GET":
        cmd_list = models.cmdlist.objects.values()
        info["cmd_list"] = cmd_list
        return render(request,"cmd.html",info)
    else:
        cmd_command = request.POST.get("cmd_command")
        cmd_type = request.POST.get("cmd_type")
        cmd_status = models.cmdlist.objects.filter(cmd_command=cmd_command).count()
        if cmd_status == 0:
            models.cmdlist.objects.create(cmd_command=cmd_command,cmd_type=cmd_type)
        else:
            pass
        return redirect("/saltconfig/cmd/")

def s_cmddel(request):
    if request.method == "GET":
        id = request.GET.get("id")
        models.cmdlist.objects.filter(id=id).delete()
        return redirect("/saltconfig/cmd/")
    else:
        pass


def s_codeupdate(request):
    if request.method == "GET":
        id = request.GET.get("id")
        salt_info = models.saltconfig.objects.filter(id=id).values()[0]
        # print(salt_info)
        gitlab = salt_info["s_gitlab"]
        salt_server_ip = salt_info["s_ip"]
        salt_code_home = settings.SALTSTACK_CODE_DIR + salt_info["s_name"]
        tmp_dir = salt_code_home + "/" + gitlab.split('/')[1].split('.')[0]
        if os.path.exists(salt_code_home) :

            os.chdir(salt_code_home + "/" + gitlab.split('/')[1].split('.')[0] )
            t = subprocess.Popen('git pull && rsync -avz   -e "ssh  -o PubkeyAuthentication=yes   -o stricthostkeychecking=no" %s/* %s:%s' %(tmp_dir,salt_server_ip,salt_info["s_file_roots"]),stdout=subprocess.PIPE,shell=True)

            return HttpResponse( t.stdout.read(),content_type="html")
        else:
            os.mkdir(salt_code_home)
            os.chdir(salt_code_home)
            t = subprocess.Popen('mkdir /srv/salt -p && mkdir /svr/pillar -p && git clone %s && rsync -avz   -e "ssh  -o PubkeyAuthentication=yes   -o stricthostkeychecking=no" %s/* %s:%s' % (gitlab,tmp_dir, salt_server_ip,salt_info["s_file_roots"]), stdout=subprocess.PIPE,
                             shell=True)
            return HttpResponse(t.stdout.read(),content_type="html")

def s_codeinit(request):
    if request.method == "GET":
        id =request.GET.get("id")
        salt_info = models.saltconfig.objects.filter(id=id).values()[0]
        login_type =salt_info["s_login"]
        salt_verion = salt_info["s_version"]
        salt_ip = salt_info["s_ip"]
        ssh_info = models.sysconfig.objects.values()[0]
        ssh_key = ssh_info["ssh_key"]
        ssh_user = ssh_info["ssh_user"]
        ssh_port = ssh_info["ssh_port"]
        ssh_pwd = ssh_info["ssh_pwd"]
        f = open("/root/.ssh/id_rsa.pub", mode="r")
        root_key = f.readlines()[0]
        f.close()
        info = b""
        if login_type == "1":
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname=salt_ip, port=ssh_port, username=ssh_user, password=ssh_pwd)
            stdin, stdout, stderr = ssh.exec_command('yum install %s -y' % (salt_verion))
            info = info + b"----yum install salt_version-------\n" + stdout.read() + stderr.read()
            stdin, stdout, stderr = ssh.exec_command('yum install salt-master  -y')
            info = info + b"----yum install salt-master -y -------\n" + stdout.read() + stderr.read()
            stdin, stdout, stderr = ssh.exec_command('yum install rsync -y')
            info = info + b"----yum install rsync -y -------\n" +stdout.read() + stderr.read()
            # stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (ssh_key))
            info = info + b"----ssh-key -------\n"  + stdout.read() + stderr.read()
            stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (root_key))
            info = info +  b"----root-key -------\n"  + stdout.read() + stderr.read()
            ssh.close()

        else:
            f = open("/tmp/id_rsa",mode="w")
            f.write(ssh_key)
            f.close()
            private_key = paramiko.RSAKey.from_private_key_file('/tmp/id_rsa')

            # 创建SSH对象
            ssh = paramiko.SSHClient()
            # 允许连接不在know_hosts文件中的主机
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # 连接服务器
            ssh.connect(hostname=salt_ip, port=ssh_port, username=ssh_user, pkey=private_key)

            # 执行命令

            stdin, stdout, stderr = ssh.exec_command('yum install %s -y' % (salt_verion))
            info = info + b"----yum install salt_version-------\n" + stdout.read() + stderr.read()
            stdin, stdout, stderr = ssh.exec_command('yum install salt-master  -y')
            info = info + b"----yum install salt-master -y -------\n" + stdout.read() + stderr.read()
            stdin, stdout, stderr = ssh.exec_command('yum install rsync -y')
            info = info + b"----yum install rsync -y -------\n" + stdout.read() + stderr.read()
            # stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (ssh_key))
            info = info + b"----ssh-key -------\n" + stdout.read() + stderr.read()
            stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (root_key))
            info = info + b"----root-key -------\n" + stdout.read() + stderr.read()

            # 关闭连接
            ssh.close()

        models.saltconfig.objects.filter(s_ip=salt_ip).update(s_init=1)
        return HttpResponse(info,content_type="html")
    else:
        print("3333333333333333333333")

def s_admin(request):
    info = {}
    my_name = request.session.get('username')
    info["my_name"] = my_name
    if request.method == "GET":
        cmd_list = models.cmdlist.objects.values()
        info["cmd_list"] = cmd_list
        return render(request,"saltconfig_admin.html",info)
    else:
        fun_num = request.POST.get("fun_num")
        cmd = request.POST.get("cmd")
        # print(cmd)
        id = request.GET.get("id")
        salt_ip = models.saltconfig.objects.filter(id=id).values()[0]["s_ip"]
        result = subprocess.Popen("ssh %s  '%s'" % (salt_ip, cmd), stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True)
        cmd_list = models.cmdlist.objects.values()

        if fun_num =="1" :
            info = {}
            info["result1"] = result.stdout.read().decode()
            info["cmd_list"] = cmd_list
            return render(request,"saltconfig_admin.html",info)
        elif fun_num == "2":
            info = {}
            info["cmd_list"] = cmd_list
            info["result2"] = result.stdout.read().decode()
            return render(request, "saltconfig_admin.html", info)
        elif fun_num == "3":
            info = {}
            s_cmd = request.POST.getlist("s_cmd")
            info["cmd_list"] = cmd_list
            obj = models.saltconfig.objects.get(id=id)
            obj.s_cmd.set(s_cmd)
            return render(request, "saltconfig_admin.html",info)
        elif fun_num == "4":
            info = {}
            info["result4"] = result.stdout.read().decode()
            info["cmd_list"] = cmd_list
            return render(request, "saltconfig_admin.html", info)







